package com.byx.chatclient.factory;

import com.byx.chatclient.config.ServerProperties;
import com.byx.chatclient.entity.Result;
import com.byx.chatclient.utils.EnumSerializer;
import com.byx.chatclient.utils.OkHttpUtils;
import com.google.gson.GsonBuilder;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * RetrofitFactory
 *
 * @author Superb
 * @date 2021/3/31 21:22
 */
public class RetrofitFactory {
    private static Retrofit singleton;
    private static final Map<Class<?>,Object> map = new ConcurrentHashMap<>();

    public static void init(){
        if (singleton == null) {
//                    GsonBuilder gsonBuilder = new GsonBuilder();
//                    gsonBuilder.registerTypeHierarchyAdapter(Result.class,new EnumSerializer());
//                    GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gsonBuilder.create());
            singleton = new Retrofit.Builder()
                    .baseUrl(ServerProperties.WEB_SERVER_URL)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(OkHttpUtils.getInstance())
                    .build();
        }
    }

    public static Retrofit getRetrofit(){
        if(singleton == null){
            synchronized (RetrofitFactory.class){
                init();
            }
        }
        return singleton;
    }

    public static <T> T createApi(Class<T> clazz){
        return getRetrofit().create(clazz);
    }

    public static <T> T getBean(Class<T> clazz){
        T t = (T) map.get(clazz);
        if (t == null){
            synchronized (RetrofitFactory.class){
                T nt = getRetrofit().create(clazz);
                map.put(clazz,nt);
                return nt;
            }
        }else {
            return t;
        }
    }
}
